//
//  PaymentRecordVC.m
//  CenturyCity
//
//  Created by beisheng03 on 2018/1/3.
//  Copyright © 2018年 beisheng. All rights reserved.
//PaymentRecord

#import "PaymentRecordVC.h"
#import "PaymentRecordCell.h"
#import "PaymentRecordHeader.h"
#import "PaymentSDWModel.h"
#import "PaymentSDSubModel.h"
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>

#import "PaySuccessJumpVC.h"

#import "PayFaildJumpVC.h"
@interface PaymentRecordVC ()
@property (nonatomic, assign) NSInteger curpage;
@property (nonatomic, assign) NSString *pageCount;

@property (nonatomic, assign) NSString *totalCount;

@property (nonatomic, strong) NSMutableArray<PaymentSDSubModel *> *dataModels;

@property (nonatomic, strong) NSString *payType;

@property (nonatomic, strong) PaymentSDWModel *payModel;

/** <#note#> */
@property (nonatomic, strong) NSString *payTag;

/** <#note#> */

@end

@implementation PaymentRecordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.payTag = @"0";
    
    if ([self.type isEqualToString:@"0"]) {
        
        self.navigationItem.title = @"";
        
    } else if ([self.type isEqualToString:@"1"]) {
        
        self.navigationItem.title = @"电费清单";
      

    }else  if ([self.type isEqualToString:@"2"]){
        
          self.navigationItem.title = @"网费清单";

    }else{
        
      
  self.navigationItem.title = @"话费清单";
        
    }
    
    
 
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.plainTableView.backgroundColor = viewBgGrey;
    
    
    self.plainTableView.rowHeight = UITableViewAutomaticDimension;
    
    self.plainTableView.estimatedRowHeight = 100;
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([PaymentRecordCell class]) bundle:nil] forCellReuseIdentifier:[PaymentRecordCell identifierStr]];
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([PaymentRecordHeader class]) bundle:nil] forHeaderFooterViewReuseIdentifier:[PaymentRecordHeader identifierStr]];
    
//
    
    MJWeakSelf
    self.plainTableView.mj_header = [XMGRefreshHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadData];
        
    }];
    
    [weakSelf.plainTableView.mj_header beginRefreshing];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(WXApiDidSuccessNotification) name:WXApiDidSuccessNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(WXApiDidFailNotification) name:WXApiDidFailNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AlipayDidSuccessNotification) name:AlipayDidSuccessNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AlipayDidFailNotification) name:AlipayDidFailNotification object:nil];

    
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(myCellPayBtnDidTap:) name:@"MyCellPayBtnDidTap" object:nil];
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    self.payTag = @"0";
    
}


- (void)myCellPayBtnDidTap:(NSNotification *)notfi{
    
    self.payModel = notfi.object;
    
    [self goToPay];
    
}





- (void)WXApiDidSuccessNotification{
    
    
    [self loadData];
    
}

- (void)WXApiDidFailNotification{
    
//    NSLog(@"%@",[NSThread currentThread]);
    
    if ([self.payTag isEqualToString:@"0"]) {
        
         [SVProgressHUD showInfoWithStatus:@"支付失败!"];
    }
    
    
   
    
}

- (void)AlipayDidSuccessNotification{
    
    [self loadData];

    
}


- (void)AlipayDidFailNotification{
    
//    NSLog(@"%@",[NSThread currentThread]);

    if ([self.payTag isEqualToString:@"0"]) {
        
        [SVProgressHUD showInfoWithStatus:@"支付失败!"];
    }

    
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}


- (void)loadData{
    
    
    
    self.curpage = 1;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"page"] = @"1";
    parameters[@"pagesize"] = @"20";
    parameters[@"type"] = self.type;
    parameters[@"uid"] = myViewModel.user.uid;

    //    keyword
    
    //    parameters[@"uid"] = myViewModel.user.uid;
    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:GET_METHOD URLPath:@"Order/virtualOrderList" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
                                                MYJSONSTR
            
//                                [[responseObject[@"data"][@"data"] firstObject]  propertyCode];
            
            weakSelf.pageCount = responseObject[@"data"][@"page_count"];
            
            weakSelf.totalCount = responseObject[@"data"][@"total_count"];
            
            
            weakSelf.dataModels = [PaymentSDSubModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"data"]];
            
            //[weakSelf.dataModels removeAllObjects];
            //weakSelf.totalCount = @"0";
            //NSLog(@"%ld",weakSelf.dataModels.count);
            
            if ([weakSelf.totalCount isEqualToString:@"0"]) {
                
                [weakSelf.plainTableView.mj_header endRefreshing];

                
            } else {
                
                
//                for (PaymentSDWModel *tep in weakSelf.dataModels) {
//                    tep.return_img = @"http://image.it168.com/n/0x0/8/8387/8387273.jpg";
//                }
                
                [weakSelf cachePictures:weakSelf.dataModels];
            
            }
            
        }else {
            
            [weakSelf.plainTableView.mj_header endRefreshing];
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
    }];
    

}





- (void)cachePictures:(NSMutableArray<PaymentSDSubModel *> *)models{
    
    
//    dispatch_group_t group = dispatch_group_create();
//
//    for (PaymentSDSubModel *model in self.dataModels) {
//
//        for (PaymentSDWModel *sub in model.lists) {
//
//            dispatch_group_enter(group);
//
//
//            [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:sub.return_img] options:kNilOptions progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//
//                dispatch_group_leave(group);
//
//            }];
//
//
//        }
//
//
//
//
//
//
//    }
//
    
    MJWeakSelf;
    
//    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    
        weakSelf.plainTableView.mj_footer = [XMGRefreshFooter footerWithRefreshingBlock:^{
            
            [weakSelf loadMoreData];
            
        }];
        
        [weakSelf.plainTableView.mj_footer resetNoMoreData];
        
        
        if ([weakSelf.pageCount isEqualToString:@"1"]) {
            
            [weakSelf.plainTableView.mj_footer endRefreshingWithNoMoreData];
            
        }
        
        [weakSelf.plainTableView.mj_header endRefreshing];
        
        
        
        [weakSelf.plainTableView reloadData];
        
        
//    });
    
  
    
    
}






- (void)loadMoreData{
    
    self.curpage ++;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"pagesize"] = @"20";
    parameters[@"page"] = [NSString stringWithFormat:@"%ld",(long)self.curpage];
    parameters[@"type"] = self.type;
    parameters[@"uid"] = myViewModel.user.uid;

    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools] sendRequestWithHttpMethod:GET_METHOD URLPath:@"Order/virtualOrderList" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
            NSMutableArray<PaymentSDSubModel *> *temp = [PaymentSDSubModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"data"]];
            
            
            
            
            [weakSelf.dataModels addObjectsFromArray:temp];
            
            
            [weakSelf cacheMorePictures:temp];
            
//            if (weakSelf.pageCount.integerValue == self.curpage) {
//
//                [weakSelf.plainTableView.mj_footer endRefreshingWithNoMoreData];
//
//            } else {
//
//                [weakSelf.plainTableView.mj_footer endRefreshing];
//
//
//            }
//
//
//            [weakSelf.plainTableView reloadData];
//
        }else{
            
            [weakSelf.plainTableView.mj_footer endRefreshing];
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
    }];
    
    
    
}


- (void)cacheMorePictures:(NSMutableArray<PaymentSDSubModel *> *)models{
    
    
    dispatch_group_t group = dispatch_group_create();
    
    for (PaymentSDSubModel *model in models) {
        
        for (PaymentSDWModel *sub in model.lists) {
            dispatch_group_enter(group);
            [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:sub.return_img] options:kNilOptions progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                
                dispatch_group_leave(group);
                
            }];
        }
        
        
        
       
        
        
        
    }
    
    
    MJWeakSelf;
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        if (weakSelf.pageCount.integerValue == self.curpage) {
            
            [weakSelf.plainTableView.mj_footer endRefreshingWithNoMoreData];
            
        } else {
            
            [weakSelf.plainTableView.mj_footer endRefreshing];
            
            
        }
        
        
        [weakSelf.plainTableView reloadData];
        
        
    });
    
    
    
}



#pragma mark - tableviewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    if (self.dataModels == nil) {
        
        return 0;
        
    } else {
     
            return self.dataModels.count;
        
    }
    

 
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.dataModels == nil) {
        
        return 0;
        
    } else {
        
        if (self.dataModels.count == 0) {
            
            return 1;
            
        } else {
            
            return self.dataModels[section].lists.count;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.dataModels.count == 0) {
        
//        PaymentRecordCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[PaymentRecordCell identifierStr]];
        
        
        return [[UITableViewCell alloc]init];
        
        
    } else {
        
        PaymentRecordCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[PaymentRecordCell identifierStr]];
        
        tableCell.index = indexPath;
        
        tableCell.type = self.type;
        
        tableCell.model = self.dataModels[indexPath.section].lists[indexPath.row];
        
        return tableCell;
        
    }
    
   
}



- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.00001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 36;
    
}



- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *temp = [[UIView alloc]init];
    temp.backgroundColor = [UIColor whiteColor];
    return temp;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    PaymentRecordHeader *temp = (PaymentRecordHeader *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:[PaymentRecordHeader identifierStr]];

    temp.dataStr = self.dataModels[section].datetime;
    
    return temp;
    
//    UIView *temp = [[UIView alloc]init];
//    temp.backgroundColor = [UIColor whiteColor];
//    return temp;
//
  
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PaymentSDWModel *model = self.dataModels[indexPath.section].lists[indexPath.row];

    if ([model.pay_status isEqualToString:@"0"]) {
        [self jumpFailWith:model.out_trade_no];
    } else {
        [self jumpSuccessWith:model.out_trade_no];
    }
    
}


- (void)jumpSuccessWith:(NSString *)out_trade_no{

//        self.payTag = @"1";
    
        PaySuccessJumpVC *jump = [[PaySuccessJumpVC alloc]init];
        
        jump.order_id = out_trade_no;
        
        [self.navigationController pushViewController:jump animated:YES];
}

- (void)jumpFailWith:(NSString *)out_trade_no{

        self.payTag = @"1";

        PayFaildJumpVC *jump = [[PayFaildJumpVC alloc]init];
        
        jump.order_id = out_trade_no;
    
        [self.navigationController pushViewController:jump animated:YES];
    
}




- (void)goToPay{
    
    MJWeakSelf;
    UIAlertController *contr = [UIAlertController alertControllerWithTitle:@"选择支付方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action0 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    [contr addAction:action0];
    
    
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"微信支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        weakSelf.payType = @"1";
        
        [weakSelf wachatPay];
        
    }];
    
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"支付宝支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        weakSelf.payType = @"2";
        
        [weakSelf alipayPayWith];
        
    }];
    
    
    
    [contr addAction:action1];
    [contr addAction:action2];
    
    
    [self presentViewController:contr animated:YES completion:nil];
    
}





- (void)alipayPayWith{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"payment"] = self.payModel.pay_rmb;
    parameters[@"out_trade_no"] = self.payModel.out_trade_no;
    parameters[@"pay_type"] = self.payType;
    
    [SVProgressHUD showWithStatus:@"订单确认中..."];
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Pay/pay_order" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        
        if (!error) {
            
            [SVProgressHUD dismiss];
            
            [[AlipaySDK defaultService] payOrder:responseObject[@"data"] fromScheme:@"com.beisheng.feifubao" callback:^(NSDictionary *resultDic) {
                
                
                //                NSLog(@"reslut = %@",resultDic);
                
            }];
            
            
        } else {
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
        
    }];
    
}


- (void)wachatPay{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"payment"] = self.payModel.pay_rmb;
    parameters[@"out_trade_no"] = self.payModel.out_trade_no;
    parameters[@"pay_type"] = self.payType;
    
    [SVProgressHUD showWithStatus:@"订单确认中..."];
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Pay/pay_order" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        
        if (!error) {
            
            [SVProgressHUD dismiss];
            
            //            MYJSONSTR;
            
            [self WXPayWithDic:responseObject[@"data"]];
            
            
        } else {
            
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
        
    }];
    
    
}



- (void)WXPayWithDic:(NSDictionary *)dic{
    
    
    //需要创建这个支付对象
    PayReq *req   = [[PayReq alloc] init];
    //由用户微信号和AppID组成的唯一标识，用于校验微信用户
    req.openID = dic[@"appid"];
    
    // 商家id，在注册的时候给的
    req.partnerId = dic[@"partnerid"];
    
    // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
    req.prepayId  = dic[@"prepayid"];
    
    // 根据财付通文档填写的数据和签名
    
    //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
    req.package   = dic[@"pkg"];
    
    // 随机编码，为了防止重复的，在后台生成
    req.nonceStr  = dic[@"noncestr"];
    
    // 这个是时间戳，也是在后台生成的，为了验证支付的
    NSString * stamp = dic[@"timestamp"];
    
    req.timeStamp = stamp.intValue;
    
    // 这个签名也是后台做的
    req.sign = dic[@"sign"];
    
    //发送请求到微信，等待微信返回onResp
    [WXApi sendReq:req];
}




- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    
    
    
    
    
    
}



@end
